﻿<%@ WebHandler Language="C#" Class="allotOperate" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;

public class allotOperate : AjaxHandlerBase {

    override public void RequestProcess(HttpContext context)
    {
        //获取操作方式
        string type = "";
        string houseid = "";
        string userid = "";
        string odep = "";
        string ndep = "";
        string ouser = "";
        string nuser = "";
            
        StringBuilder output = new StringBuilder();
        
        if (!string.IsNullOrEmpty(context.Request.QueryString["type"]))
        {
            type = context.Request.QueryString["type"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["houseid"]))
        {
            houseid = context.Request.QueryString["houseid"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["userid"]))
        {
            userid = context.Request.QueryString["userid"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["odep"]))
        {
            odep = context.Request.QueryString["odep"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["ndep"]))
        {
            ndep = context.Request.QueryString["ndep"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["ouser"]))
        {
            ouser = context.Request.QueryString["ouser"];
        }
        if (!string.IsNullOrEmpty(context.Request.QueryString["nuser"]))
        {
            nuser = context.Request.QueryString["nuser"];
        }
        
        switch (type)
        {
            case "hand"://手动分配房源
                output = HouseByHand(houseid,userid);
                break;
            case "hand_custom": //手动分配客源
                output = CustomerByHand(houseid, userid);
                break;
            case "toUser"://分配房源给个人
                output = HouseToUser(odep,ndep,ouser,nuser);
                break;
            case "toUser_custom"://分配客源给个人
                output = CustomToUser(odep, ndep, ouser, nuser);
                break;
            case "toDep"://分配房源给门店
                output = HouseToDep(odep, ndep, ouser);
                break;
            case "toDep_custom"://分配客源给门店
                output = CustomToDep(odep, ndep, ouser);
                break;
            case "toAvg"://平均分配房源给门店
                output = HouseToAvg(odep, ndep, ouser);
                break;
            case "toAvg_custom"://平均分配客源给门店
                output = CustomToAvg(odep, ndep, ouser);
                break;
            default:
                break;
        }

        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        context.Response.Write(output);
    }
 
   override public bool IsReusable {
        get {
            return false;
        }
    }

   //手动分配客源给某人
   private StringBuilder CustomerByHand(string houseid, string userid)
   {
       StringBuilder sb = new StringBuilder();
       string strSql = "";
       Chenxin.Lib.Passport.Entity.Hr_UserInfo userinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(new Guid(userid));
       if (userinfo != null && houseid.Length > 0)
       {
           //添加房源分配日志并修改原房源记录
           strSql += String.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate() from Customer_BaseInfo where CustomerId in ({6});", userinfo.UserId, userinfo.UserName, userinfo.DepartId, userinfo.DepartName, CurrentUserInfo.UserId, CurrentUserInfo.UserName, houseid);
           strSql += String.Format("update Customer_BaseInfo set OprPersonId='{0}',OprPerson='{1}',OprDepartId='{2}',OprDepart='{3}' where CustomerId in ({4});", userinfo.UserId, userinfo.UserName, userinfo.DepartId, userinfo.DepartName, houseid);

           bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
           if (flag)
               sb.Append("{success:'1'}");
           else
               sb.Append("{success:'0',txt:'没有可分配的客源'}");
       }
       else
       {
           sb.Append("{success:'0',txt:'分配房源操作失败！'}");
       }    
       return sb;
   }
    
    
    //手动分配房源给某人
    private StringBuilder HouseByHand(string houseid,string userid)
    {
        StringBuilder sb = new StringBuilder();
        string strSql = "";
        Chenxin.Lib.Passport.Entity.Hr_UserInfo userinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(new Guid(userid));
        if (userinfo != null&&houseid.Length>0)
        {
            //添加房源分配日志并修改原房源记录
            strSql += String.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate() from House_BaseInfo where HouseId in ({6});", userinfo.UserId, userinfo.UserName, userinfo.DepartId, userinfo.DepartName, CurrentUserInfo.UserId, CurrentUserInfo.UserName, houseid);
            strSql  += String.Format("update House_BaseInfo set OprPersonId='{0}',OprPerson='{1}',OprDepartId='{2}',OprDepart='{3}' where HouseId in ({4});", userinfo.UserId, userinfo.UserName, userinfo.DepartId, userinfo.DepartName, houseid);
            
            //添加房源的客户分配日志并修改客户记录
            strSql += string.Format("insert into Customer_AllotLogs select newid(),Customer_BaseInfo.CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate() from dbo.Customer_BaseInfo inner join (select CustomerId from house_baseinfo where HouseId in({6}))a on Customer_BaseInfo.CustomerId =a.CustomerId;", userinfo.UserId, userinfo.UserName, userinfo.DepartId, userinfo.DepartName, CurrentUserInfo.UserId, CurrentUserInfo.UserName, houseid);
            strSql += string.Format("update Customer_BaseInfo set OprPersonId='{0}',OprPerson='{1}',OprDepartId='{2}',OprDepart='{3}' from dbo.Customer_BaseInfo inner join (select CustomerId from house_baseinfo where HouseId in ({4}))a on Customer_BaseInfo.CustomerId =a.CustomerId;", userinfo.UserId, userinfo.UserName, userinfo.DepartId, userinfo.DepartName, houseid);
            
            bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
            if (flag)
                sb.Append("{success:'1'}");
            else
                sb.Append("{success:'0',txt:'没有可分配的房源'}");
        }
        else
        {
            sb.Append("{success:'0',txt:'分配房源操作失败！'}");
        }        
        return sb;
    }


    //快速分配房源给某人
    private StringBuilder HouseToUser(string odep, string ndep, string ouser, string nuser)
    {
        StringBuilder sb = new StringBuilder();
        string[] ndep_array = ndep.Split(',');// 1：ID，0：名字
        string[] nuser_array = nuser.Split(',');// 1：ID，0：名字
        string struserid = "";
        if (ouser.Length > 0)
            struserid = " and House_BaseInfo.OprPersonId='" + ouser + "'";
        
        string strSql = "";
        //添加房源分配日志并修改原房源记录
        strSql += String.Format("insert into House_AllotLogs select newid(),HouseId,HouseCode,Community+BuildingName+Room,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate() from House_BaseInfo where OprDepartId='{6}'{7};", nuser_array[1], nuser_array[0], ndep_array[1], ndep_array[0], CurrentUserInfo.UserId, CurrentUserInfo.UserName, odep, struserid);
        //添加客户分配日志并修改客户记录
        strSql += string.Format("insert into Customer_AllotLogs select newid(),Customer_BaseInfo.CustomerId,CustomerCode,Customer_BaseInfo.CustomerName,Customer_BaseInfo.OprPersonId,Customer_BaseInfo.OprPerson,Customer_BaseInfo.OprDepartId,Customer_BaseInfo.OprDepart,Customer_BaseInfo.CompanyId,Customer_BaseInfo.CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate()  from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.OprDepartId='{6}'{7};", nuser_array[1], nuser_array[0], ndep_array[1], ndep_array[0], CurrentUserInfo.UserId, CurrentUserInfo.UserName, odep, struserid);

        strSql += String.Format("update House_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}' where OprDepartId='{4}'{5};", nuser_array[0], nuser_array[1], ndep_array[0], ndep_array[1], odep,struserid);
                
        strSql += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}' from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.OprDepartId='{4}'{5};", nuser_array[0], nuser_array[1], ndep_array[0], ndep_array[1], odep, struserid);
        
        bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
        if (flag)
            sb.Append("{success:'1'}");
        else
            sb.Append("{success:'0',txt:'没有可分配的房源'}");

        return sb;
    }

    //快速分配客源给某人
    private StringBuilder CustomToUser(string odep, string ndep, string ouser, string nuser)
    {
        StringBuilder sb = new StringBuilder();
        string[] ndep_array = ndep.Split(',');// 1：ID，0：名字
        string[] nuser_array = nuser.Split(',');// 1：ID，0：名字
        string struserid = "";
        if (ouser.Length > 0)
            struserid = " and OprPersonId='" + ouser + "'";

        string strSql = "";
        //添加房源分配日志并修改原房源记录
        strSql += String.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate() from Customer_BaseInfo where OprDepartId='{6}'{7};", nuser_array[1], nuser_array[0], ndep_array[1], ndep_array[0], CurrentUserInfo.UserId, CurrentUserInfo.UserName, odep, struserid);

        strSql += String.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}' where OprDepartId='{4}'{5};", nuser_array[0], nuser_array[1], ndep_array[0], ndep_array[1], odep, struserid);

        bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
        if (flag)
            sb.Append("{success:'1'}");
        else
            sb.Append("{success:'0',txt:'没有可分配的客源'}");

        return sb;
    }


    //快速分配房源给某店
    private StringBuilder HouseToDep(string odep, string ndep, string ouser)
    {
        StringBuilder sb = new StringBuilder();
        string[] ndep_array = ndep.Split(',');// 1：ID，0：名字
        string strSql = "";

        string struserid = "";
        if (ouser.Length > 0)
            struserid = " and OprPersonId='" + ouser + "'";

        //添加房源分配日志并修改原房源记录
        strSql += String.Format("insert into House_AllotLogs select newid(),HouseId,HouseCode,Community+BuildingName+Room,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,OprPersonId,OprPerson,'{0}','{1}','{2}','{3}',getdate() from House_BaseInfo where OprDepartId='{4}'{5};", ndep_array[1], ndep_array[0], CurrentUserInfo.UserId, CurrentUserInfo.UserName, odep, struserid);
        //添加客户分配日志并修改客户记录
        strSql += string.Format("insert into Customer_AllotLogs select newid(),Customer_BaseInfo.CustomerId,CustomerCode,Customer_BaseInfo.CustomerName,Customer_BaseInfo.OprPersonId,Customer_BaseInfo.OprPerson,Customer_BaseInfo.OprDepartId,Customer_BaseInfo.OprDepart,Customer_BaseInfo.CompanyId,Customer_BaseInfo.CompanyName,Customer_BaseInfo.OprPersonId,Customer_BaseInfo.OprPerson,'{0}','{1}','{2}','{3}',getdate()  from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.OprDepartId='{4}'{5};", ndep_array[1], ndep_array[0], CurrentUserInfo.UserId, CurrentUserInfo.UserName, odep, struserid);

        strSql += String.Format("update House_BaseInfo set OprDepart='{0}',OprDepartId='{1}' where OprDepartId='{2}'{3};", ndep_array[0], ndep_array[1], odep,struserid);
        strSql += string.Format("update Customer_BaseInfo set OprDepart='{0}',OprDepartId='{1}' from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.OprDepartId='{2}'{3};", ndep_array[0], ndep_array[1], odep, struserid);

        bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
        if (flag)
            sb.Append("{success:'1'}");
        else
            sb.Append("{success:'0',txt:'没有可分配的房源'}");

        return sb;
    }

    //快速分配客源给某店
    private StringBuilder CustomToDep(string odep, string ndep, string ouser)
    {
        StringBuilder sb = new StringBuilder();
        string[] ndep_array = ndep.Split(',');// 1：ID，0：名字
        string strSql = "";

        string struserid = "";
        if (ouser.Length > 0)
            struserid = " and OprPersonId='" + ouser + "'";

        //添加房源分配日志并修改原房源记录
        strSql += String.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,OprPersonId,OprPerson,'{0}','{1}','{2}','{3}',getdate() from Customer_BaseInfo where OprDepartId='{4}'{5};", ndep_array[1], ndep_array[0], CurrentUserInfo.UserId, CurrentUserInfo.UserName, odep, struserid);

        strSql += String.Format("update Customer_BaseInfo set OprDepart='{0}',OprDepartId='{1}' where OprDepartId='{2}'{3};", ndep_array[0], ndep_array[1], odep, struserid);

        bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
        if (flag)
            sb.Append("{success:'1'}");
        else
            sb.Append("{success:'0',txt:'没有可分配的客源'}");

        return sb;
    }

    
    //平均分配房源
    private StringBuilder HouseToAvg(string odep, string ndep, string ouser)
    {
        StringBuilder sb = new StringBuilder();
        string[] ndep_array = ndep.Split(',');// 1：ID，0：名字
        string housecount_sql=String.Format("OprDepartId='{0}'",odep);
        
        if (ouser.Length > 0)
            housecount_sql += " and OprPersonId='" + ouser + "'";
        string usercount_sql = String.Format("DepartId='{0}' and Status='1'", ndep_array[1]);
        DataSet house_ds = Chenxin.Lib.House.DAL.House_BaseInfo.GetList(housecount_sql);
        DataSet user_ds = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetList(usercount_sql);
        int house_sum = house_ds.Tables[0].Rows.Count;
        int user_sum = user_ds.Tables[0].Rows.Count;
        
        if(house_sum==0)
            sb.Append("{success:'0',txt:'没有可分配的房源'}");
        else if (user_sum == 0)
            sb.Append("{success:'0',txt:'接受门店没有可接受的员工'}");
        else
        {
            string str = "";
            for (int i = 0; i < house_sum; )
            {
                for (int j = 0; j < user_sum; j++)
                {
                    if (i >= house_sum)
                        break;
                    //添加房源分配日志并修改原房源记录
                    str += String.Format("insert into House_AllotLogs select newid(),HouseId,HouseCode,Community+BuildingName+Room,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate() from House_BaseInfo where HouseId='{6}';", user_ds.Tables[0].Rows[j]["UserId"], user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["DepartId"], user_ds.Tables[0].Rows[j]["DepartName"], CurrentUserInfo.UserId, CurrentUserInfo.UserName, house_ds.Tables[0].Rows[i]["HouseId"]);
                    //添加客户分配日志并修改客户记录
                    str += string.Format("insert into Customer_AllotLogs select newid(),Customer_BaseInfo.CustomerId,CustomerCode,Customer_BaseInfo.CustomerName,Customer_BaseInfo.OprPersonId,Customer_BaseInfo.OprPerson,Customer_BaseInfo.OprDepartId,Customer_BaseInfo.OprDepart,Customer_BaseInfo.CompanyId,Customer_BaseInfo.CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate()  from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.HouseId='{6}';", user_ds.Tables[0].Rows[j]["UserId"], user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["DepartId"], user_ds.Tables[0].Rows[j]["DepartName"], CurrentUserInfo.UserId, CurrentUserInfo.UserName, house_ds.Tables[0].Rows[i]["HouseId"]);

                    str += string.Format("update House_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}' where HouseId='{4}';", user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["UserId"], user_ds.Tables[0].Rows[j]["DepartName"], user_ds.Tables[0].Rows[j]["DepartId"], house_ds.Tables[0].Rows[i]["HouseId"]);
                    str += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}' from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.HouseId='{4}';", user_ds.Tables[0].Rows[j]["UserId"], user_ds.Tables[0].Rows[j]["DepartName"], user_ds.Tables[0].Rows[j]["DepartId"], house_ds.Tables[0].Rows[i]["HouseId"]);

                    i++;
                }
            }
            bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(str);
            if (flag)
                sb.Append("{success:'1'}");
            else
                sb.Append("{success:'0',txt:'没有可分配的房源'}");
        }
        return sb;
    }

    //平均分配客源
    private StringBuilder CustomToAvg(string odep, string ndep, string ouser)
    {
        StringBuilder sb = new StringBuilder();
        string[] ndep_array = ndep.Split(',');// 1：ID，0：名字
        string housecount_sql = String.Format("OprDepartId='{0}'", odep);

        if (ouser.Length > 0)
            housecount_sql += " and OprPersonId='" + ouser + "'";
        string usercount_sql = String.Format("DepartId='{0}' and Status='1'", ndep_array[1]);
        DataSet house_ds = Chenxin.Lib.House.DAL.Customer_BaseInfo.GetList(housecount_sql);
        DataSet user_ds = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetList(usercount_sql);
        int house_sum = house_ds.Tables[0].Rows.Count;
        int user_sum = user_ds.Tables[0].Rows.Count;

        if (house_sum == 0)
            sb.Append("{success:'0',txt:'没有可分配的客源'}");
        else if (user_sum == 0)
            sb.Append("{success:'0',txt:'接受门店没有可接受的员工'}");
        else
        {
            string str = "";
            for (int i = 0; i < house_sum; )
            {
                for (int j = 0; j < user_sum; j++)
                {
                    if (i >= house_sum)
                        break;
                    //添加房源分配日志并修改原房源记录
                    str += String.Format("insert into Customer_AllotLogs select newid(),CustomerId,CustomerCode,CustomerName,OprPersonId,OprPerson,OprDepartId,OprDepart,CompanyId,CompanyName,'{0}','{1}','{2}','{3}','{4}','{5}',getdate() from Customer_BaseInfo where CustomerId='{6}';", user_ds.Tables[0].Rows[j]["UserId"], user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["DepartId"], user_ds.Tables[0].Rows[j]["DepartName"], CurrentUserInfo.UserId, CurrentUserInfo.UserName, house_ds.Tables[0].Rows[i]["HouseId"]);

                    str += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}' where CustomerId='{4}';", user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["UserId"], user_ds.Tables[0].Rows[j]["DepartName"], user_ds.Tables[0].Rows[j]["DepartId"], house_ds.Tables[0].Rows[i]["HouseId"]);
                    i++;
                }
            }
            bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(str);
            if (flag)
                sb.Append("{success:'1'}");
            else
                sb.Append("{success:'0',txt:'没有可分配的客源'}");
        }
        return sb;
    }

}